<script setup lang="ts">
import { ref, reactive, onMounted, shallowRef, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, View } from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  title: '',
  categoryId: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const viewVisible = ref(false)

// 表单数据
const form = reactive({
  id: '',
  title: '',
  content: '',
  summary: '',
  categoryId: '',
  status: 1,
  isTop: 0,
  isRecommend: 0,
  viewCount: 0,
  coverImage: ''
})

// 查看数据
const viewData = reactive({
  title: '',
  content: '',
  summary: '',
  categoryName: '',
  status: 1,
  isTop: 0,
  isRecommend: 0,
  viewCount: 0,
  coverImage: '',
  createTime: '',
  updateTime: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ]
}

// 分类选项
const categoryOptions = ref([
  { id: 1, name: '技术分享' },
  { id: 2, name: '生活随笔' },
  { id: 3, name: '学习笔记' },
  { id: 4, name: '项目经验' }
])

// wangEditor编辑器配置
const editorRef = shallowRef()
const editorConfig = {
  placeholder: '请输入文章内容...',
  MENU_CONF: {}
}

// 编辑器内容
const editorValue = ref('<p></p>')

// 编辑器创建完成
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 编辑器内容变化
const handleChange = (editor) => {
  form.content = editor.getHtml()
}

// 组件销毁时，销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 工具栏配置
const toolbarConfig = {
  excludeKeys: [
    'insertVideo',
    'uploadVideo',
    'group-video',
    'insertTable',
    'group-image'
  ]
}

// 表单引用
const formRef = ref()

// 初始化数据
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    tableData.value = [
      { id: 1, title: 'Vue 3.0 新特性介绍', summary: 'Vue 3.0 带来了许多新特性，包括Composition API、更好的TypeScript支持等。', categoryId: 1, categoryName: '技术分享', status: 1, isTop: 1, isRecommend: 1, viewCount: 1000, coverImage: 'https://picsum.photos/seed/vue3/300/200.jpg', createTime: '2023-01-01 10:00:00', updateTime: '2023-01-01 10:00:00' },
      { id: 2, title: '如何构建高性能的前端应用', summary: '本文将介绍如何构建高性能的前端应用，包括代码分割、懒加载等技术。', categoryId: 1, categoryName: '技术分享', status: 1, isTop: 0, isRecommend: 1, viewCount: 800, coverImage: 'https://picsum.photos/seed/performance/300/200.jpg', createTime: '2023-01-02 10:00:00', updateTime: '2023-01-02 10:00:00' },
      { id: 3, title: '我的编程学习之路', summary: '分享我从零开始学习编程的经历和心得体会。', categoryId: 2, categoryName: '生活随笔', status: 1, isTop: 0, isRecommend: 0, viewCount: 500, coverImage: 'https://picsum.photos/seed/learning/300/200.jpg', createTime: '2023-01-03 10:00:00', updateTime: '2023-01-03 10:00:00' }
    ]
    pagination.total = 3
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加文章'
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 显示编辑对话框
const showEditDialog = (row: any) => {
  dialogTitle.value = '编辑文章'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  form.id = row.id
  form.title = row.title
  // 确保内容不为空
  form.content = row.content || '<p></p>'
  form.summary = row.summary
  form.categoryId = row.categoryId
  form.status = row.status
  form.isTop = row.isTop
  form.isRecommend = row.isRecommend
  form.viewCount = row.viewCount
  form.coverImage = row.coverImage
}

// 查看文章
const handleView = (row: any) => {
  // 填充查看数据
  viewData.title = row.title
  viewData.content = row.content
  viewData.summary = row.summary
  viewData.categoryName = row.categoryName
  viewData.status = row.status
  viewData.isTop = row.isTop
  viewData.isRecommend = row.isRecommend
  viewData.viewCount = row.viewCount
  viewData.coverImage = row.coverImage
  viewData.createTime = row.createTime
  viewData.updateTime = row.updateTime
  
  viewVisible.value = true
}

// 删除文章
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该文章吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除API请求
    setTimeout(() => {
      ElMessage.success('删除成功')
      fetchData()
    }, 500)
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      // 模拟API请求
      setTimeout(() => {
        ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
        dialogVisible.value = false
        fetchData()
      }, 500)
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = ''
  form.title = ''
  form.content = ''
  form.summary = ''
  form.categoryId = ''
  form.status = 1
  form.isTop = 0
  form.isRecommend = 0
  form.viewCount = 0
  form.coverImage = ''
}

// 状态格式化
const statusFormatter = (row: any) => {
  return row.status === 1 ? '发布' : '草稿'
}

// 状态标签类型
const statusTagType = (status: number) => {
  return status === 1 ? 'success' : 'info'
}

// 置顶格式化
const isTopFormatter = (row: any) => {
  return row.isTop === 1 ? '是' : '否'
}

// 置顶标签类型
const isTopTagType = (isTop: number) => {
  return isTop === 1 ? 'danger' : 'info'
}

// 推荐格式化
const isRecommendFormatter = (row: any) => {
  return row.isRecommend === 1 ? '是' : '否'
}

// 推荐标签类型
const isRecommendTagType = (isRecommend: number) => {
  return isRecommend === 1 ? 'warning' : 'info'
}

// 分类名称格式化
const categoryFormatter = (row: any) => {
  const category = categoryOptions.value.find(item => item.id === row.categoryId)
  return category ? category.name : '未知分类'
}
</script>

<template>
  <div class="article-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="文章标题">
          <el-input v-model="searchForm.title" placeholder="请输入文章标题" clearable />
        </el-form-item>
        <el-form-item label="文章分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择文章分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="发布" :value="1" />
            <el-option label="草稿" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-button type="primary" :icon="Plus" @click="showAddDialog">添加文章</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="文章标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="summary" label="摘要" min-width="300" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="120">
          <template #default="{ row }">
            {{ categoryFormatter(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusFormatter(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isTop" label="置顶" width="80">
          <template #default="{ row }">
            <el-tag :type="isTopTagType(row.isTop)">
              {{ isTopFormatter(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isRecommend" label="推荐" width="80">
          <template #default="{ row }">
            <el-tag :type="isRecommendTagType(row.isRecommend)">
              {{ isRecommendFormatter(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览量" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button type="primary" :icon="View" size="small" @click="handleView(row)">查看</el-button>
              <el-button type="success" :icon="Edit" size="small" @click="showEditDialog(row)">编辑</el-button>
              <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择文章分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章摘要">
          <el-input v-model="form.summary" type="textarea" :rows="3" placeholder="请输入文章摘要" />
        </el-form-item>
        <el-form-item label="封面图片">
          <el-input v-model="form.coverImage" placeholder="请输入封面图片URL" />
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <div style="border: 1px solid #ccc; z-index: 100;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 400px; overflow-y: hidden;"
              v-model="form.content"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
              @onChange="handleChange"
            />
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="其他设置">
          <el-checkbox :model-value="form.isTop === 1" @change="form.isTop = $event ? 1 : 0">置顶</el-checkbox>
          <el-checkbox :model-value="form.isRecommend === 1" @change="form.isRecommend = $event ? 1 : 0">推荐</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog
      v-model="viewVisible"
      title="查看文章"
      width="800px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="文章标题">{{ viewData.title }}</el-descriptions-item>
        <el-descriptions-item label="文章分类">{{ viewData.categoryName }}</el-descriptions-item>
        <el-descriptions-item label="文章摘要">{{ viewData.summary }}</el-descriptions-item>
        <el-descriptions-item label="封面图片">
          <el-image v-if="viewData.coverImage" :src="viewData.coverImage" fit="cover" style="width: 200px; height: 120px;" />
        </el-descriptions-item>
        <el-descriptions-item label="文章内容">
          <div v-html="viewData.content"></div>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewData.status === 1 ? 'success' : 'info'">
            {{ viewData.status === 1 ? '发布' : '草稿' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="置顶">
          <el-tag :type="viewData.isTop === 1 ? 'danger' : 'info'">
            {{ viewData.isTop === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="推荐">
          <el-tag :type="viewData.isRecommend === 1 ? 'warning' : 'info'">
            {{ viewData.isRecommend === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="浏览量">{{ viewData.viewCount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ viewData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ viewData.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.article-container {
  padding: 20px;
  height: calc(100vh - 30px);
  overflow-y: auto;
  box-sizing: border-box;
}

.search-card {
  margin-bottom: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .article-container {
    padding: 10px;
  }
  
  .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .el-table .cell {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  
  .operation-area .el-button {
    margin-bottom: 10px;
  }
}

/* 表格内容溢出处理 */
.el-table .cell {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

/* 对话框样式优化 */
.el-dialog__body {
  padding: 20px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

/* 图片预览样式 */
.el-image {
  border-radius: 4px;
  overflow: hidden;
}

/* 按钮间距 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 标签样式优化 */
.el-tag {
  margin-right: 5px;
}

/* 搜索区域样式优化 */
.search-card .el-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.search-card .el-form-item:last-child {
  margin-right: 0;
}

/* 增加选择框宽度 */
.search-card .el-select {
  width: 150px;
}

/* 分页样式优化 */
.pagination-container .el-pagination {
  justify-content: flex-end;
}

/* 操作列按钮样式 */
.operation-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: nowrap;
  justify-content: center;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .article-container {
    padding: 10px;
  }
  
  .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .el-table .cell {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  
  .operation-area .el-button {
    margin-bottom: 10px;
  }
  
  .operation-buttons {
    flex-direction: column;
    gap: 3px;
  }
}
</style>